import request from '@/utils/request'
import type {
  Customer,
  CustomerContact,
  CustomerTrace,
  CustomerChance,
  CustomerLog,
  StageOption,
  ApiResponse,
  CustomerListParams,
} from '@/types/customer'

// 重新导出类型以便使用
export type {
  Customer,
  CustomerContact,
  CustomerTrace,
  CustomerChance,
  CustomerLog,
  StageOption,
  CustomerListParams,
}

// 定义分页响应类型
interface PaginatedResponse<T> {
  list: T[]
  total: number
  page: number
  limit: number
}

export const customerApi = {
  // 获取客户列表
  getCustomerList: (params: any): Promise<ApiResponse<PaginatedResponse<Customer>>> => {
    return request({
      url: '/api/customer/customer/list',
      method: 'get',
      params,
    })
  },

  // 获取主客户列表
  getMainCustomerList: (params: any): Promise<ApiResponse<PaginatedResponse<Customer>>> => {
    return request({
      url: '/api/customer/customer/list',
      method: 'get',
      params: {
        ...params,
        is_primary: 1, // 只获取主客户
      },
    })
  },

  // 搜索客户（远程搜索）
  searchCustomers: (keyword: string): Promise<ApiResponse<Customer[]>> => {
    return request({
      url: '/api/customer/customer/search',
      method: 'get',
      params: { keyword },
    })
  },

  // 分配客户
  distributeCustomer: (data: any): Promise<ApiResponse<any>> => {
    return request({
      url: '/api/customer/customer/assign',
      method: 'post',
      data,
    })
  },

  // 锁定/解锁客户
  lockCustomer: (data: any): Promise<ApiResponse<any>> => {
    return request({
      url: '/api/customer/customer/lock',
      method: 'post',
      data,
    })
  },

  // 删除客户
  deleteCustomer: (data: any): Promise<ApiResponse<any>> => {
    return request({
      url: '/api/customer/customer/del',
      method: 'delete',
      data,
    })
  },

  // 获取客户跟进记录
  getTraceList: (params: any): Promise<ApiResponse<CustomerTrace[]>> => {
    return request({
      url: '/api/customer/trace/list',
      method: 'get',
      params,
    })
  },

  // 添加客户跟进记录
  addCustomerTrace: (data: any): Promise<ApiResponse<any>> => {
    // 确保next_time是数字而非null
    if (data.next_time === null || data.next_time === undefined) {
      data.next_time = 0
    }

    return request({
      url: '/api/customer/trace/add',
      method: 'post',
      data,
    })
  },

  // 编辑客户跟进记录
  editCustomerTrace: (data: any): Promise<ApiResponse<any>> => {
    // 确保next_time是数字而非null
    if (data.next_time === null || data.next_time === undefined) {
      data.next_time = 0
    }

    return request({
      url: '/api/customer/trace/edit',
      method: 'put',
      data,
    })
  },

  // 删除客户跟进记录
  deleteCustomerTrace: (id: number): Promise<ApiResponse<any>> => {
    return request({
      url: '/api/customer/trace/del',
      method: 'delete',
      data: { id },
    })
  },

  // 获取客户跟进记录详情
  getTraceDetail: (id: number): Promise<ApiResponse<CustomerTrace>> => {
    return request({
      url: '/api/customer/trace/view',
      method: 'get',
      params: { id },
    })
  },

  // 获取销售机会列表
  getChanceList: (params: any): Promise<ApiResponse<CustomerChance[]>> => {
    return request({
      url: '/api/customer/chance/list',
      method: 'get',
      params,
    })
  },

  /**
   * 获取单个联系人详情
   */
  getContactDetail: (id: number): Promise<ApiResponse<CustomerContact>> => {
    return request({
      url: '/api/customer/contact/view',
      method: 'get',
      params: { id },
    })
  },

  // 获取销售阶段选项
  getChanceStageOptions: (): Promise<ApiResponse<StageOption[]>> => {
    return request({
      url: '/api/customer/chance/stageOptions',
      method: 'get',
    })
  },

  // 获取联系人数据
  getContactList: (params: any): Promise<ApiResponse<PaginatedResponse<CustomerContact>>> => {
    return request({
      url: '/api/customer/contact/list',
      method: 'get',
      params,
    })
  },

  // 获取所有联系人数据（不依赖客户ID）
  getAllContactList: (params: any): Promise<ApiResponse<PaginatedResponse<CustomerContact>>> => {
    return request({
      url: '/api/customer/contact/list',
      method: 'get',
      params,
    })
  },

  // 设置默认联系人
  setContact: (data: any) => {
    return request({
      url: '/api/customer/contact/set_default',
      method: 'post',
      data,
    })
  },

  // 添加附件
  addFile: (data: any) => {
    return request({
      url: '/api/customer/file/add',
      method: 'post',
      data,
    })
  },

  // 删除附件
  deleteFile: (data: any) => {
    return request({
      url: '/api/customer/file/del',
      method: 'delete',
      data,
    })
  },

  // 获取操作日志列表
  getLogList: (params: any): Promise<ApiResponse<CustomerLog[]>> => {
    return request({
      url: '/api/customer/log/list',
      method: 'get',
      params,
    })
  },

  // 客户管理相关接口（从 customer/customer.ts 合并）
  // 获取客户列表
  getCustomerDetailList: (params?: any) => {
    return request({
      url: '/api/customer/customer/list',
      method: 'get',
      params,
    })
  },

  // 查看客户详情
  viewCustomer: (params?: any): Promise<ApiResponse<Customer>> => {
    return request({
      url: '/api/customer/customer/view',
      method: 'get',
      params,
    })
  },

  // 查看客户详情（别名方法，用于兼容不同的调用方式）
  getCustomerDetail: (params?: any): Promise<ApiResponse<Customer>> => {
    // 确保contract_workflow参数被正确传递，默认为1以绕过权限检查
    const requestParams = {
      ...params,
      contract_workflow: params?.contract_workflow || 1,
    }
    return request({
      url: '/api/customer/customer/view',
      method: 'get',
      params: requestParams,
    })
  },

  /**
   * 获取客户等级选项（从oa_basic_customer表获取，通过grade/set接口）
   * @param params 可选参数
   * @returns Promise<ApiResponse<Array<{id: string | number, title?: string, name?: string}>>> 返回客户等级选项数据，用于下拉选择控件
   * @description 从后端grade/set接口获取客户等级字典数据，该接口实际查询的是oa_basic_customer表
   * @example 返回格式：{ code: 0, msg: '获取成功', data: [{ id: '1', title: '普通客户' }, ...] }
   * @note 当API调用失败或无数据时，返回预设的静态默认数据
   */
  getCustomerGradeOptions: (
    params?: any
  ): Promise<ApiResponse<Array<{ id: string | number; title?: string; name?: string }>>> => {
    return request({
      url: '/api/customer/grade/set',
      method: 'get',
      params,
    }).then((response: any) => {
      // 确保返回格式统一，优先使用title字段
      if (response.code === 0 && Array.isArray(response.data)) {
        return response
      } else if (response.data?.code === 0 && Array.isArray(response.data.data)) {
        return {
          code: response.data.code,
          msg: response.data.msg,
          data: response.data.data.map((item: any) => ({
            id: item.id,
            title: item.title || item.name || `等级${item.id}`,
          })),
        }
      }
      // 返回默认选项作为后备
      return {
        code: 0,
        msg: '获取成功',
        data: [
          { id: '1', title: '普通客户' },
          { id: '2', title: '重要客户' },
          { id: '3', title: 'VIP客户' },
        ],
      }
    })
  },

  /**
   * 获取客户状态选项（从oa_basic_customer表获取，type=1）
   * @param params 可选参数
   * @returns Promise<ApiResponse<Array<{id: string | number, name: string}>>> 返回客户状态选项数据，用于下拉选择控件
   * @description 从后端oa_basic_customer表获取客户状态字典数据，type=1表示客户状态类型
   * @example 返回格式：{ code: 0, msg: '获取成功', data: [{ id: 2, name: '会员' }, ...] }
   * @note 当API调用失败或无数据时，返回预设的静态默认数据
   */
  getCustomerStatusOptions: (
    params?: any
  ): Promise<ApiResponse<Array<{ id: string | number; name: string }>>> => {
    return request({
      url: '/api/customer/customer/basic_data',
      method: 'get',
      params: { ...params, type: 1 }, // 确保查询type=1的记录
    }).then((response: any) => {
      // 转换数据格式，确保返回{id, name}格式
      // 修复：正确处理API返回的格式 {code: 0, msg: "获取成功", data: [...]}
      if (response.code === 0 && Array.isArray(response.data)) {
        return {
          code: response.code,
          msg: response.msg,
          data: response.data.map((item: any) => ({
            id: item.id,
            name: item.title || item.name || `状态${item.id}`,
          })),
        }
      }
      // 同时兼容旧格式 {data: {code: 0, data: [...]}}
      else if (response.data?.code === 0 && Array.isArray(response.data.data)) {
        return {
          code: response.data.code,
          msg: response.data.msg,
          data: response.data.data.map((item: any) => ({
            id: item.id,
            name: item.title || item.name || `状态${item.id}`,
          })),
        }
      }
      // 返回默认状态选项作为后备
      return {
        code: 0,
        msg: '获取成功',
        data: [
          { id: 2, name: '会员' },
          { id: 3, name: '非会员' },
          { id: 20, name: '过期会员' },
        ],
      }
    })
  },

  /**
   * 获取客户来源选项（从oa_basic_customer表获取，type=3）
   * @param params 可选参数
   * @returns Promise<ApiResponse<Array<{id: string | number, title?: string, name?: string}>>> 返回客户来源选项数据，用于下拉选择控件
   * @description 从后端source/set接口获取客户来源字典数据，该接口实际查询的是oa_basic_customer表，对应type=3
   * @example 返回格式：{ code: 0, msg: '获取成功', data: [{ id: '1', title: '网站' }, ...] }
   * @note 当API调用失败或无数据时，返回预设的静态默认数据
   */
  getSourceOptions: (
    params?: any
  ): Promise<ApiResponse<Array<{ id: string | number; title?: string; name?: string }>>> => {
    return request({
      url: '/api/customer/source/set',
      method: 'get',
      params,
    }).then((response: any) => {
      // 确保返回格式统一，优先使用title字段
      if (response.code === 0 && Array.isArray(response.data)) {
        return response
      } else if (response.data?.code === 0 && Array.isArray(response.data.data)) {
        return {
          code: response.data.code,
          msg: response.data.msg,
          data: response.data.data.map((item: any) => ({
            id: item.id,
            title: item.title || item.name || `来源${item.id}`,
          })),
        }
      }
      // 返回默认选项作为后备
      return {
        code: 0,
        msg: '获取成功',
        data: [
          { id: '1', title: '网站' },
          { id: '2', title: '电话' },
          { id: '3', title: '展会' },
          { id: '4', title: '转介绍' },
          { id: '5', title: '广告' },
          { id: '6', title: '社交媒体' },
          { id: '7', title: '搜索引擎' },
          { id: '8', title: '其他渠道' },
        ],
      }
    })
  },

  // 获取员工列表
  getAdminList: (params?: any): Promise<ApiResponse<Array<{ id: number; name: string }>>> => {
    return request({
      url: '/api/user/user/admin_list',
      method: 'get',
      params,
    })
  },

  // 获取地区数据
  getRegionList: (params?: any): Promise<ApiResponse<any[]>> => {
    return request({
      url: '/api/system/region/list',
      method: 'get',
      params,
    })
  },

  // 新增客户
  addCustomer: (data: any): Promise<ApiResponse<any>> => {
    return request({
      url: '/api/customer/customer/add',
      method: 'post',
      data,
    })
  },

  // 编辑客户
  editCustomer: (data: any): Promise<ApiResponse<any>> => {
    return request({
      url: '/api/customer/customer/edit',
      method: 'put',
      data,
    })
  },

  // 更新客户（编辑客户的别名）
  updateCustomer: (data: any): Promise<ApiResponse<any>> => {
    return request({
      url: '/api/customer/customer/edit',
      method: 'put',
      data,
    })
  },

  // 删除客户
  deleteCustomerDetail: (data: any) => {
    return request({
      url: '/api/customer/customer/del',
      method: 'delete',
      data,
    })
  },

  // 客户状态更新
  updateCustomerStatus: (data: any) => {
    return request({
      url: '/api/customer/customer/lock',
      method: 'post',
      data,
    })
  },

  // 客户分配
  assignCustomer: (data: any) => {
    return request({
      url: '/api/customer/customer/assign',
      method: 'post',
      data,
    })
  },

  // 添加联系人
  addContact: (data: any): Promise<ApiResponse<any>> => {
    return request({
      url: '/api/customer/contact/add',
      method: 'post',
      data,
    })
  },

  // 编辑联系人
  editContact: (data: any): Promise<ApiResponse<any>> => {
    return request({
      url: '/api/customer/contact/edit',
      method: 'put',
      data,
    })
  },

  // 设置默认联系人
  setDefaultContact: (data: any): Promise<ApiResponse<any>> => {
    return request({
      url: '/api/customer/contact/set_default',
      method: 'post',
      data,
    })
  },

  // 删除联系人
  deleteContact: (id: number): Promise<ApiResponse<any>> => {
    return request({
      url: '/api/customer/contact/del',
      method: 'delete',
      data: { id }, // 将ID作为数据传递
    })
  },

  // 废弃客户
  discardCustomer: (data: any): Promise<ApiResponse<any>> => {
    return request({
      url: '/api/customer/customer/discard',
      method: 'post',
      data,
    })
  },

  // 获取废弃客户列表
  getDiscardCustomerList: (
    params?: any
  ): Promise<
    ApiResponse<{ list: Customer[]; total: number; page: number; limit: number; pages: number }>
  > => {
    return request({
      url: '/api/customer/customer/list',
      method: 'get',
      params,
    })
  },

  // 客户统计
  getCustomerStatistics: (params?: any): Promise<ApiResponse<any>> => {
    return request({
      url: '/api/customer/customer/list',
      method: 'get',
      params,
    })
  },

  // 删除销售机会
  deleteCustomerChance: (id: number): Promise<ApiResponse<any>> => {
    return request({
      url: '/api/customer/chance/del',
      method: 'delete',
      data: { id },
    })
  },

  // 新增销售机会
  addCustomerChance: (data: any): Promise<ApiResponse<any>> => {
    return request({
      url: '/api/customer/chance/add',
      method: 'post',
      data,
    })
  },

  // 编辑销售机会
  editCustomerChance: (data: any): Promise<ApiResponse<any>> => {
    return request({
      url: '/api/customer/chance/edit',
      method: 'put',
      data,
    })
  },

  // 获取选项数据（统一获取客户来源、等级等选项）
  getOptions: (): Promise<ApiResponse<any>> => {
    return request({
      url: '/api/customer/customer/basic_data',
      method: 'get',
    })
  },

  // 获取客户状态选项（会员状态）
  getStatusOptions: (): Promise<ApiResponse<any>> => {
    return request({
      url: '/api/customer/customer/basic_data',
      method: 'get',
      params: { type: 1 }, // 查询oa_basic_customer表中type=1的记录，即会员状态选项
    }).then((response: any) => {
      // 处理后端返回的数据格式，转换为前端需要的格式
      // 修复：正确处理API返回的格式 {code: 0, msg: "获取成功", data: [...]}
      if (response.code === 0 && Array.isArray(response.data)) {
        return {
          code: response.code,
          msg: response.msg,
          data: {
            customer_status: response.data.map((item: any) => ({
              value: item.id,
              label: item.title || item.name || `状态${item.id}`,
            })),
          },
        }
      }
      // 同时兼容旧格式 {data: {code: 0, data: [...]}}
      else if (response.data?.code === 0 && Array.isArray(response.data.data)) {
        return {
          code: response.data.code,
          msg: response.data.msg,
          data: {
            customer_status: response.data.data.map((item: any) => ({
              value: item.id,
              label: item.title || item.name || `状态${item.id}`,
            })),
          },
        }
      }
      // 返回默认状态选项作为后备
      return {
        code: 0,
        msg: '获取成功',
        data: {
          customer_status: [
            { value: 2, label: '会员' },
            { value: 3, label: '非会员' },
            { value: 20, label: '过期会员' },
          ],
        },
      }
    })
  },

  // 获取客户统计信息
  getStatistics: (): Promise<ApiResponse<any>> => {
    return request({
      url: '/api/customer/customer/statistics',
      method: 'get',
    })
  },
}
